package controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.DealModel;
import models.OrderFeedbackModel;
import models.OrderModel;
import models.OrderProductModel;
import models.ProductModel;
import models.UserModel;
import admin.data.DealData;
import admin.data.IdCountData;
import admin.data.ProductData;
import data.OrderData;
import data.OrderFeedbackData;

@SuppressWarnings("serial")
public class OrderServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(OrderServlet.class
			.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		String[] splitted = request.getRequestURI().split("/");
		if (splitted.length > 2) {
			String action = splitted[2];
			String id = "";
			if (action.equals("mua")) {
				id = splitted[3];
				DealModel deal = DealData.getById(id);
				if (deal != null) {
					List<ProductModel> listProduct = ProductData
							.getByDealId(deal.getDealId());
					request.setAttribute("deal", deal);
					request.setAttribute("listProduct", listProduct);
					request.getRequestDispatcher("/pages/cart.jsp").forward(
							request, response);
				} else {
					request.getRequestDispatcher("/pages/error.jsp").forward(
							request, response);
				}
			} else if (action.equals("xoa")) {
				Cookie cookies[] = request.getCookies();
				if (cookies != null) {
					for (int i = 0; i < cookies.length; i++) {
						if (cookies[i].getName().equals("city")) {
							request.setAttribute("city", cookies[i].getValue());
							break;
						}
					}
				}
				request.setAttribute("deal", null);
				request.getRequestDispatcher("/pages/cart.jsp").forward(
						request, response);
			} else if (action.equals("huy")) {
				HttpSession session = request.getSession();
				UserModel user = (UserModel) session
						.getAttribute("user_logged_in");
				id = splitted[3];				
				
				OrderModel order = OrderData.getOrder(id);
				if (order != null && user != null
						&& order.getUsername().equals(user.getUsername())) {					
					for (String string : order.getListOrderProduct()) {
						OrderProductModel orderProduct = new OrderProductModel();
						orderProduct.getValueFromString(string);
						ProductModel product = ProductData.getById(orderProduct
								.getProductId());
						if (product != null) {
							product.setTotalOrderQuantity(product
									.getTotalOrderQuantity()
									- orderProduct.getQuantity());
							ProductData.insert(product);
						}						
					}
					DealModel deal = DealData
							.getById(order.getDealId());
					if (deal != null) {
						int amount = deal.getAmount()
								- order.getQuantity();
						if (amount < 0) {
							amount = 0;
						}
						deal.setAmount(amount);
						if (deal.getEndTime().compareTo(
								Calendar.getInstance().getTime()) > 0
								&& deal.getAmount() < deal.getLimit()) {
							deal.setStatus(2);
						}
						DealData.insert(deal);
					}
					order.setStatus(5);
					OrderData.insert(order);
					response.sendRedirect("/quan-ly-don-hang");
				} else {
					request.getRequestDispatcher("/pages/error.jsp").forward(
							request, response);
				}
			} else if (action.equals("xem")) {
				HttpSession session = request.getSession();
				UserModel user = (UserModel) session
						.getAttribute("user_logged_in");
				id = splitted[3];
				OrderModel order = OrderData.getOrder(id);
				if (order != null && user != null && order.getUsername().equals(user.getUsername())) {
					request.setAttribute("user", user);
					request.setAttribute("order", order);
					request.getRequestDispatcher("/pages/order_detail.jsp")
							.forward(request, response);
				} else {
					request.setAttribute("sms", "Trang này không tồn tại hoặc bạn cần đăng nhập để truy cập.");
					request.getRequestDispatcher("/pages/no_cart.jsp").forward(
							request, response);
				}
			} else if (action.equals("in")) {
				HttpSession session = request.getSession();
				UserModel user = (UserModel) session
						.getAttribute("user_logged_in");
				id = splitted[3];
				OrderModel order = OrderData.getOrder(id);
				if (order != null && user != null) {
					if (order.getUsername().equals(user.getUsername())) {
						request.setAttribute("user", user);
						request.setAttribute("order", order);
						request.getRequestDispatcher("/pages/order_print.jsp")
								.forward(request, response);
					} else {
						request.getRequestDispatcher("/pages/error.jsp")
								.forward(request, response);
					}
				} else {
					request.getRequestDispatcher("/pages/error.jsp").forward(
							request, response);
				}
			}
		} else {
			request.getRequestDispatcher("/pages/cart.jsp").forward(request,
					response);
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			String action = req.getParameter("action");
			if (action != null && action.equals("feedback")) {
				HttpSession session = req.getSession();
				UserModel user = (UserModel) session
						.getAttribute("user_logged_in");
				String username = req.getParameter("username");
				String fbContent = req.getParameter("fbContent");
				String orderId = req.getParameter("orderId");
				OrderModel order = OrderData.getOrder(orderId);
				if (order != null && user != null) {
					TreeMap check = new TreeMap();
					if (username == null || username.isEmpty()) {
						check.put("username", "Vui lòng nhập họ và tên.");
					}
					if (fbContent == null || fbContent.isEmpty()) {
						check.put("fbContent",
								"Vui lòng nhập thông tin phản hồi.");
					}
					if (check.size() != 0) {
						req.setAttribute("check", check);
					} else {
						OrderFeedbackData fbData = new OrderFeedbackData();
						OrderFeedbackModel fb = new OrderFeedbackModel();
						fb.setUsername(username);
						fb.setContent(fbContent);
						fb.setFeedbackId(IdUniqueHelper.getId());
						fb.setOrderId(order.getOrderId());
						fb.setStatus(1);
						fbData.insert(fb);
					}
					req.setAttribute("user", user);
					req.setAttribute("order", order);
					req.getRequestDispatcher("/pages/order_detail.jsp")
							.forward(req, resp);
				} else {
					req.getRequestDispatcher("/pages/error.jsp").forward(req,
							resp);
				}
			} else {
				String strDealId = req.getParameter("dealId");
				if (strDealId != null && strDealId.length() > 0) {
					DealModel deal = DealData.getById(strDealId);
					if (deal != null) {
						int quantity = 0;
						List<ProductModel> listProduct = ProductData
								.getByDealId(deal.getDealId());
						List<String> listStringProduct = new ArrayList<String>();
						if (listProduct != null && listProduct.size() > 0) {
							for (ProductModel productModel : listProduct) {
								try {
									OrderProductModel oP = new OrderProductModel();
									oP.setName(productModel.getName());
									oP.setProductId(productModel.getProductId());
									String strQuantity = req
											.getParameter(productModel
													.getProductId().toString());
									oP.setQuantity(Integer
											.parseInt(strQuantity));
									quantity += oP.getQuantity();
									if (oP.getQuantity() > 0) {
										listStringProduct.add(oP.toString());
									}
								} catch (Exception e) {
									log.warning(e.toString());
									e.printStackTrace();
								}
							}

						}
						OrderModel order = new OrderModel();
						order.setSalername(deal.getUsername());
						order.setOrderId(deal.getDealId() + "-"
								+ IdCountData.getIdByType("2"));
						order.setDealId(deal.getDealId());
						order.setQuantity(quantity);
						order.setUnitPrice(deal.getPriceDiscount());
						order.setTotalPrice(quantity * deal.getPriceDiscount());
						HttpSession session = req.getSession();
						session.setAttribute("user_order", order);
						resp.sendRedirect("/thanh-toan");

					} else {
						System.out
								.println("Error when try to get Deal by Id ! "
										+ strDealId);
						log.warning("Error when try to get Deal by Id ! "
								+ strDealId);
						req.getRequestDispatcher("/pages/error.jsp").forward(
								req, resp);
					}
				} else {
					System.out
							.println("Error when try to get dealId Parameter ! ");
					log.warning("Error when try to get dealId Parameter ! ");
					req.getRequestDispatcher("/pages/error.jsp").forward(req,
							resp);
				}
			}
		} catch (Exception e) {
			System.out.println("Error when try to view submit order !");
			log.warning("Error when try to view submit order !");
			req.getRequestDispatcher("/pages/error.jsp").forward(req, resp);
		}

	}
}
